let fs = require("fs");
class User {
  constructor(option) {
    this.id = option.id;
    this.age = option.age;
    this.sexual = option.sexual;
    this.password = option.password;
  }
  toJson() {
    return {
      id: this.id,
      age: this.age,
      sexual: this.sexual,
      password: this.password
    };
  }
}
const PATH = "server/user.json";
let UserList = {};
class UserControl {
  status = -1;
  $start(callback, fail) {
    this.read(() => {
      this.status = 0;
      callback();
    }, fail);
  }
  add(option, callback, fail) {
    //检查用户是否存在，如果存在，则报错用户已存在。
    let user = UserList[option.id];
    if (user) {
      fail && fail(`用户${option.id}已存在`);
      return;
    }
    //创建一个新的用户
    user = new User(option);
    UserList[user.id] = user;
    // callback && callback();
    //保存文件
    this.save(option, callback, () => {
      delete UserList[user.id];
      fail();
    });
  }
  check({ id, password }, callback, fail) {
    let user = UserList[id];
    if (!user) {
      fail(`用户${id}不存在`);
      return;
    }
    if (String(user.password) !== String(password)) {
      fail(`密码错误`);
      return;
    }
    callback();
  }
  delete({ id }, callback, fail) {
    let user = UserList[id];
    if (!user) {
      fail(`用户${id}不存在`);
      return;
    }
    delete UserList[id];
    // callback();
    this.save({ id }, callback, fail);
  }
  update(option, callback, fail) {
    let user = UserList[option.id];
    if (!user) {
      return fail(`用户${option.id}不存在`);
    }
    for (let key in option) {
      user[key] = option[key];
    }
    callback();
  }
  init(data) {
    if (data.content) {
      UserList = {};
      for (let userOpt of data.content) {
        UserList[userOpt.id] = new User(userOpt);
      }
    }
  }
  get({ id }, callback, fail) {
    if (id) {
      let user = UserList[id];
      if (user) {
        callback(user.toJson());
      } else {
        fail({
          msg: `找不到用户[${id}]`,
          status: -1
        });
      }
    } else {
      let r = [];
      for (let id in UserList) {
        let user = UserList[id];
        r.push(user.toJson());
      }
      callback(r);
    }
  }
  read(callback, fail) {
    let ctx = this;

    try {
      let data = fs.readFileSync(PATH, "utf8");
      if (typeof data == "string") {
        data = JSON.parse(data);
      }
      ctx.init(data);
      callback(data);
    } catch (e) {
      console.error(e);
      fail(e);
    }
  }
  save(options, callback, fail) {
    // if (typeof data == "object") {
    //   data = JSON.stringify(data);
    // }
    let data = { content: [] };
    for (let key in UserList) {
      let v = UserList[key];
      data.content.push(v.toJson());
    }

    fs.writeFile(PATH, JSON.stringify(data), "utf8", err => {
      if (err) {
        fali && fail(err);
      } else {
        callback && callback();
      }
    });
  }
}

module.exports = {
  UserControl: new UserControl()
};
